import axios from 'axios'
import router from '@/router/index'
import $message from '@/utils/message'
import { getToken } from '@/request/token'
const request = axios.create({
  baseURL: 'http://127.0.0.1:8081',
  timeout: 30000,
  headers: {
    'Content-Type': "application/json"
  }
})

// 请求拦截
request.interceptors.request.use(config => {
  config.headers['Authorization'] = getToken()
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截
request.interceptors.response.use(
  response => {
    let res = response.data
    if (res.code === 200) {
      return response
    } else {
      let errmessage = !res.msg ? '系统异常' : res.msg
      $message('error', errmessage)
      if (res.msg === "请先登陆！") {
        router.push("/login")                                                                                                           
      }
      return Promise.reject(res.msg)
    }
  },
  error => {
    let errmes = ''
    console.log(error)
    if (error.response.data) {
      errmes = error.response.data.msg
    }
    if (error.response.status === 403) {
      router.push("/login")
    }
    $message('error', errmes, 2000)
    return Promise.reject(error)
  }
)

export default request
